// 性能优化工具函数
const performanceUtils = {
    // 防抖函数
    debounce: function(func, wait, immediate) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                timeout = null;
                if (!immediate) func(...args);
            };
            const callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func(...args);
        };
    },
    
    // 节流函数
    throttle: function(func, limit) {
        let inThrottle;
        return function(...args) {
            if (!inThrottle) {
                func.apply(this, args);
                inThrottle = true;
                setTimeout(() => inThrottle = false, limit);
            }
        };
    },
    
    // 性能监控
    measurePerformance: function(name, fn) {
        const start = performance.now();
        const result = fn();
        const end = performance.now();
        this.logPerformance(`${name} 执行时间: ${(end - start).toFixed(2)}ms`);
        return result;
    },
    
    // 安全的日志记录
    logPerformance: function(message) {
        if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
            console.log(message);
        }
    },
    
    // Core Web Vitals监控
    initWebVitals: function() {
        // LCP (Largest Contentful Paint)
        new PerformanceObserver((entryList) => {
            const entries = entryList.getEntries();
            const lastEntry = entries[entries.length - 1];
            this.logPerformance(`LCP: ${lastEntry.startTime}`);
        }).observe({entryTypes: ['largest-contentful-paint']});
        
        // FID (First Input Delay)
        new PerformanceObserver((entryList) => {
            const entries = entryList.getEntries();
            entries.forEach(entry => {
                this.logPerformance(`FID: ${entry.processingStart - entry.startTime}`);
            });
        }).observe({entryTypes: ['first-input']});
        
        // CLS (Cumulative Layout Shift)
        let clsValue = 0;
        new PerformanceObserver((entryList) => {
            const entries = entryList.getEntries();
            entries.forEach(entry => {
                if (!entry.hadRecentInput) {
                    clsValue += entry.value;
                }
            });
            this.logPerformance(`CLS: ${clsValue}`);
        }).observe({entryTypes: ['layout-shift']});
    }
};

// 安全性工具函数
const securityUtils = {
    // 清理HTML内容
    sanitizeHTML: function(str) {
        const temp = document.createElement('div');
        temp.textContent = str;
        return temp.innerHTML;
    },
    
    // 验证URL
    isValidURL: function(string) {
        try {
            const url = new URL(string);
            return url.protocol === 'http:' || url.protocol === 'https:';
        } catch (_) {
            return false;
        }
    },
    
    // CSRF令牌生成
    generateCSRFToken: function() {
        return Array.from(crypto.getRandomValues(new Uint8Array(32)))
            .map(b => b.toString(16).padStart(2, '0')).join('');
    }
};

// 图片优化工具
const imageUtils = {
    // WebP支持检测
    supportsWebP: function() {
        return new Promise((resolve) => {
            const webP = new Image();
            webP.onload = webP.onerror = () => resolve(webP.height === 2);
            webP.src = '';
        });
    },
    
    // 懒加载实现
    lazyLoad: function() {
        const images = document.querySelectorAll('img[data-src]');
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.src = img.dataset.src;
                    img.classList.remove('lazy');
                    imageObserver.unobserve(img);
                }
            });
        }, {
            rootMargin: '50px 0px',
            threshold: 0.01
        });
        
        images.forEach(img => imageObserver.observe(img));
    }
};

// 错误监控工具
const errorMonitor = {
    // 初始化错误监控
    init: function() {
        // 全局JavaScript错误捕获
        window.addEventListener('error', (event) => {
            this.logError({
                type: 'javascript',
                message: event.message,
                filename: event.filename,
                lineno: event.lineno,
                colno: event.colno,
                stack: event.error?.stack,
                timestamp: new Date().toISOString()
            });
        });
        
        // Promise未捕获错误
        window.addEventListener('unhandledrejection', (event) => {
            this.logError({
                type: 'promise',
                message: event.reason?.message || event.reason,
                stack: event.reason?.stack,
                timestamp: new Date().toISOString()
            });
        });
        
        // 资源加载错误
        window.addEventListener('error', (event) => {
            if (event.target !== window) {
                this.logError({
                    type: 'resource',
                    element: event.target.tagName,
                    source: event.target.src || event.target.href,
                    timestamp: new Date().toISOString()
                });
            }
        }, true);
    },
    
    // 错误日志记录
    logError: function(errorInfo) {
        console.error('错误监控:', errorInfo);
        
        // 存储到本地（可选择上报到服务器）
        const errors = JSON.parse(localStorage.getItem('errorLogs') || '[]');
        errors.push(errorInfo);
        
        // 保持最近100条错误记录
        if (errors.length > 100) {
            errors.splice(0, errors.length - 100);
        }
        
        localStorage.setItem('errorLogs', JSON.stringify(errors));
    },
    
    // 获取错误统计
    getErrorStats: function() {
        const errors = JSON.parse(localStorage.getItem('errorLogs') || '[]');
        const stats = {
            total: errors.length,
            javascript: errors.filter(e => e.type === 'javascript').length,
            promise: errors.filter(e => e.type === 'promise').length,
            resource: errors.filter(e => e.type === 'resource').length
        };
        return stats;
    }
};

// 可访问性增强工具
const accessibilityUtils = {
    // 初始化可访问性功能
    init: function() {
        this.addKeyboardNavigation();
        this.addAriaLabels();
        this.addFocusManagement();
    },
    
    // 键盘导航增强
    addKeyboardNavigation: function() {
        document.addEventListener('keydown', (event) => {
            // ESC键关闭模态框
            if (event.key === 'Escape') {
                const modals = document.querySelectorAll('.modal.show, .sidebar.show');
                modals.forEach(modal => modal.classList.remove('show'));
            }
            
            // Tab键焦点管理
            if (event.key === 'Tab') {
                this.manageFocusOrder(event);
            }
        });
    },
    
    // 添加ARIA标签
    addAriaLabels: function() {
        // 为按钮添加aria-label
        document.querySelectorAll('button:not([aria-label])')?.forEach(btn => {
            if (btn.textContent.trim()) {
                btn.setAttribute('aria-label', btn.textContent.trim());
            }
        });
        
        // 为链接添加aria-label
        document.querySelectorAll('a:not([aria-label])')?.forEach(link => {
            if (link.textContent.trim()) {
                link.setAttribute('aria-label', link.textContent.trim());
            }
        });
    },
    
    // 焦点管理
    addFocusManagement: function() {
        // 为所有交互元素添加焦点样式
        const style = document.createElement('style');
        style.textContent = `
            *:focus {
                outline: 2px solid #0078d4 !important;
                outline-offset: 2px !important;
            }
            .skip-link {
                position: absolute;
                top: -40px;
                left: 6px;
                background: #0078d4;
                color: white;
                padding: 8px;
                text-decoration: none;
                z-index: 10000;
            }
            .skip-link:focus {
                top: 6px;
            }
        `;
        document.head.appendChild(style);
        
        // 添加跳转链接
        const skipLink = document.createElement('a');
        skipLink.href = '#main-content';
        skipLink.className = 'skip-link';
        skipLink.textContent = '跳转到主内容';
        document.body.insertBefore(skipLink, document.body.firstChild);
    },
    
    // 焦点顺序管理
    manageFocusOrder: function(event) {
        const focusableElements = document.querySelectorAll(
            'a[href], button:not([disabled]), textarea:not([disabled]), input:not([disabled]), select:not([disabled]), [tabindex]:not([tabindex="-1"])'
        );
        
        const firstElement = focusableElements[0];
        const lastElement = focusableElements[focusableElements.length - 1];
        
        if (event.shiftKey && document.activeElement === firstElement) {
            event.preventDefault();
            lastElement.focus();
        } else if (!event.shiftKey && document.activeElement === lastElement) {
            event.preventDefault();
            firstElement.focus();
        }
    }
};

// 默认网站数据
const defaultSites = [
    { name: 'Bing', url: 'https://www.bing.com', icon: '🔍' },
    { name: 'Outlook', url: 'https://outlook.live.com', icon: '📧' },
    { name: 'Office', url: 'https://www.office.com', icon: '📄' },
    { name: 'OneDrive', url: 'https://onedrive.live.com', icon: '☁️' },
    { name: 'Teams', url: 'https://teams.microsoft.com', icon: '👥' },
    { name: 'LinkedIn', url: 'https://www.linkedin.com', icon: '💼' },
    { name: 'GitHub', url: 'https://github.com', icon: '💻' },
    { name: 'YouTube', url: 'https://www.youtube.com', icon: '📺' }
];

// 模拟新闻数据
const mockNews = [
    {
        title: '科技创新推动数字化转型加速发展',
        summary: '随着人工智能、云计算等技术的快速发展，各行各业正在经历前所未有的数字化变革...',
        source: '科技日报',
        time: '2小时前',
        image: null
    },
    {
        title: '新能源汽车市场持续增长',
        summary: '今年前三季度，新能源汽车销量同比增长超过30%，市场渗透率不断提升...',
        source: '财经网',
        time: '4小时前',
        image: null
    },
    {
        title: '教育数字化转型取得新进展',
        summary: '在线教育平台用户数量持续增长，智慧教育解决方案在全国范围内推广应用...',
        source: '教育新闻',
        time: '6小时前',
        image: null
    },
    {
        title: '绿色发展理念深入人心',
        summary: '碳中和目标推动下，清洁能源投资大幅增加，绿色金融产品创新不断涌现...',
        source: '环保时报',
        time: '8小时前',
        image: null
    }
];

// 搜索建议数据
const searchSuggestions = [
    '今日新闻',
    '天气预报',
    '必应翻译',
    '图片搜索',
    '视频搜索',
    '地图导航',
    '股票行情',
    '学习资源',
    '购物比价',
    '旅游攻略'
];

// 错误边界和性能监控
const errorHandler = {
    logError: function(error, context = '') {
        // 只在开发环境输出到控制台
        if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
            console.error(`错误 [${context}]:`, error);
        }
        
        // 记录到本地存储用于调试
        const errorLog = {
            message: error.message || error,
            stack: error.stack,
            context: context,
            timestamp: new Date().toISOString(),
            url: window.location.href
        };
        
        try {
            const errors = JSON.parse(localStorage.getItem('errorLogs') || '[]');
            errors.push(errorLog);
            localStorage.setItem('errorLogs', JSON.stringify(errors.slice(-50))); // 保留最近50条
        } catch (e) {
            // 忽略localStorage错误
        }
    },
    
    handleAsyncError: function(promise, context = '') {
        return promise.catch(error => {
            this.logError(error, context);
            return null;
        });
    }
};

// 事件监听器管理器 - 防止内存泄漏
const eventListenerManager = {
    listeners: new Map(),
    
    add: function(element, event, handler, options = {}) {
        const key = `${element.constructor.name}-${event}`;
        if (!this.listeners.has(key)) {
            this.listeners.set(key, []);
        }
        
        element.addEventListener(event, handler, options);
        this.listeners.get(key).push({ element, event, handler, options });
    },
    
    remove: function(element, event, handler) {
        const key = `${element.constructor.name}-${event}`;
        const listeners = this.listeners.get(key);
        
        if (listeners) {
            const index = listeners.findIndex(l => 
                l.element === element && l.event === event && l.handler === handler
            );
            
            if (index !== -1) {
                element.removeEventListener(event, handler);
                listeners.splice(index, 1);
            }
        }
    },
    
    cleanup: function() {
        this.listeners.forEach((listeners, key) => {
            listeners.forEach(({ element, event, handler }) => {
                try {
                    element.removeEventListener(event, handler);
                } catch (e) {
                    // 静默处理清理错误
                }
            });
        });
        this.listeners.clear();
        // 只在开发环境输出日志
        if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
            console.log('🧹 事件监听器已清理');
        }
    }
};

// 高级性能监控
const performanceMonitor = {
    startTime: performance.now(),
    metrics: {
        fcp: 0,
        lcp: 0,
        cls: 0,
        fid: 0
    },
    
    init: function() {
        this.measureFCP();
        this.measureLCP();
        this.measureCLS();
        this.measureFID();
        this.startMemoryMonitoring();
    },
    
    markLoadComplete: function() {
        const loadTime = performance.now() - this.startTime;
        if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
            console.log(`页面加载完成时间: ${loadTime.toFixed(2)}ms`);
        }
        this.logPerformanceReport();
    },
    
    measureFCP: function() {
        if ('PerformanceObserver' in window) {
            new PerformanceObserver((list) => {
                list.getEntries().forEach((entry) => {
                    if (entry.name === 'first-contentful-paint') {
                        this.metrics.fcp = entry.startTime;
                        if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                            console.log(`FCP: ${entry.startTime.toFixed(2)}ms`);
                        }
                    }
                });
            }).observe({entryTypes: ['paint']});
        }
    },
    
    measureLCP: function() {
        if ('PerformanceObserver' in window) {
            new PerformanceObserver((list) => {
                list.getEntries().forEach((entry) => {
                    this.metrics.lcp = entry.startTime;
                    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                        console.log(`LCP: ${entry.startTime.toFixed(2)}ms`);
                    }
                });
            }).observe({entryTypes: ['largest-contentful-paint']});
        }
    },
    
    measureCLS: function() {
        if ('PerformanceObserver' in window) {
            let clsValue = 0;
            new PerformanceObserver((list) => {
                list.getEntries().forEach((entry) => {
                    if (!entry.hadRecentInput) {
                        clsValue += entry.value;
                    }
                });
                this.metrics.cls = clsValue;
                if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                    console.log(`CLS: ${clsValue.toFixed(4)}`);
                }
            }).observe({entryTypes: ['layout-shift']});
        }
    },
    
    measureFID: function() {
        if ('PerformanceObserver' in window) {
            new PerformanceObserver((list) => {
                list.getEntries().forEach((entry) => {
                    this.metrics.fid = entry.processingStart - entry.startTime;
                    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                        console.log(`FID: ${this.metrics.fid.toFixed(2)}ms`);
                    }
                });
            }).observe({entryTypes: ['first-input']});
        }
    },
    
    startMemoryMonitoring: function() {
        if (performance.memory) {
            setInterval(() => {
                const used = performance.memory.usedJSHeapSize;
                const total = performance.memory.totalJSHeapSize;
                const limit = performance.memory.jsHeapSizeLimit;
                
                if (used / limit > 0.8) {
                    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                        console.warn(`内存使用率过高: ${(used/1024/1024).toFixed(2)}MB / ${(limit/1024/1024).toFixed(2)}MB`);
                    }
                }
            }, 30000); // 每30秒检查一次
        }
    },
    
    logPerformanceReport: function() {
        if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
            console.group('📊 性能报告');
            console.log(`FCP: ${this.metrics.fcp.toFixed(2)}ms`);
            console.log(`LCP: ${this.metrics.lcp.toFixed(2)}ms`);
            console.log(`CLS: ${this.metrics.cls.toFixed(4)}`);
            console.log(`FID: ${this.metrics.fid.toFixed(2)}ms`);
            
            // 性能评分
            const score = this.calculatePerformanceScore();
            console.log(`性能评分: ${score}/100`);
            console.groupEnd();
        }
    },
    
    calculatePerformanceScore: function() {
        let score = 100;
        
        // FCP评分 (目标: <1.8s)
        if (this.metrics.fcp > 1800) score -= 20;
        else if (this.metrics.fcp > 1000) score -= 10;
        
        // LCP评分 (目标: <2.5s)
        if (this.metrics.lcp > 2500) score -= 25;
        else if (this.metrics.lcp > 1500) score -= 15;
        
        // CLS评分 (目标: <0.1)
        if (this.metrics.cls > 0.25) score -= 25;
        else if (this.metrics.cls > 0.1) score -= 15;
        
        // FID评分 (目标: <100ms)
        if (this.metrics.fid > 300) score -= 20;
        else if (this.metrics.fid > 100) score -= 10;
        
        return Math.max(0, score);
    }
};

// PWA支持
const pwaManager = {
    deferredPrompt: null,
    
    init: function() {
        // 注册Service Worker
        if ('serviceWorker' in navigator) {
            navigator.serviceWorker.register('/sw.js')
                .then(registration => {
                    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                        console.log('Service Worker 注册成功:', registration);
                    }
                    
                    // 检查更新
                    registration.addEventListener('updatefound', () => {
                        const newWorker = registration.installing;
                        newWorker.addEventListener('statechange', () => {
                            if (newWorker.state === 'installed' && navigator.serviceWorker.controller) {
                                this.showUpdateNotification();
                            }
                        });
                    });
                })
                .catch(error => {
                    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                        console.error('Service Worker 注册失败:', error);
                    }
                });
        }
        
        // 监听安装提示
        window.addEventListener('beforeinstallprompt', (e) => {
            e.preventDefault();
            this.deferredPrompt = e;
            this.showInstallButton();
        });
        
        // 监听安装完成
        window.addEventListener('appinstalled', () => {
            if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                console.log('PWA 安装成功');
            }
            this.hideInstallButton();
        });
    },
    
    showInstallButton: function() {
        const installBtn = document.createElement('button');
        installBtn.textContent = '安装应用';
        installBtn.className = 'install-btn';
        installBtn.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: #0078d4;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 5px;
            cursor: pointer;
            z-index: 10000;
            font-size: 14px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        `;
        
        installBtn.addEventListener('click', () => {
            this.installApp();
        });
        
        document.body.appendChild(installBtn);
    },
    
    hideInstallButton: function() {
        const installBtn = document.querySelector('.install-btn');
        if (installBtn) {
            installBtn.remove();
        }
    },
    
    installApp: function() {
        if (this.deferredPrompt) {
            this.deferredPrompt.prompt();
            this.deferredPrompt.userChoice.then((result) => {
                if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                    if (result.outcome === 'accepted') {
                        console.log('用户接受了安装提示');
                    } else {
                        console.log('用户拒绝了安装提示');
                    }
                }
                this.deferredPrompt = null;
                this.hideInstallButton();
            });
        }
    },
    
    showUpdateNotification: function() {
        const notification = document.createElement('div');
        notification.innerHTML = `
            <div style="
                position: fixed;
                top: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: #4CAF50;
                color: white;
                padding: 15px 20px;
                border-radius: 5px;
                z-index: 10001;
                box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            ">
                新版本可用，请刷新页面更新
                <button onclick="location.reload()" style="
                    margin-left: 10px;
                    background: white;
                    color: #4CAF50;
                    border: none;
                    padding: 5px 10px;
                    border-radius: 3px;
                    cursor: pointer;
                ">刷新</button>
            </div>
        `;
        
        document.body.appendChild(notification);
        
        // 5秒后自动隐藏
        setTimeout(() => {
            notification.remove();
        }, 5000);
    }
};

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    try {
        // 初始化性能监控
        performanceMonitor.init();
        
        // 初始化Core Web Vitals监控
        performanceUtils.initWebVitals();
        
        // 初始化错误监控
        errorMonitor.init();
        
        // 初始化可访问性功能
        accessibilityUtils.init();
        
        // 初始化图片懒加载
        imageUtils.lazyLoad();
        
        // 初始化PWA
        pwaManager.init();
        
        // 初始化懒加载
        lazyLoadManager.init();
        
        // 启动缓存清理定时器
        setInterval(() => cacheManager.cleanup(), 300000); // 每5分钟清理一次
        
        // 加载核心功能
        performanceUtils.measurePerformance('初始化页面', () => initializePage());
        setupEventListeners();
        loadUserSettings();
        initializeCustomBackground();
        initializeGeolocation();
        initializeCitySearch();
        loadSidebarStates();
        
        // 标记加载完成
        performanceMonitor.markLoadComplete();
        
        // 性能优化提示
        setTimeout(() => {
            const stats = cacheManager.getStats();
            if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                console.log('📈 缓存统计:', stats);
            }
        }, 5000);
        
        // 页面加载完成后显示性能提示
        setTimeout(() => {
            performanceTipManager.showRandomTip();
        }, 3000);
        
        // 每30秒显示一次随机提示
        setInterval(() => {
            if (Math.random() < 0.3) { // 30%概率显示提示
                performanceTipManager.showRandomTip();
            }
        }, 30000);
        
        // 页面卸载时清理资源
        window.addEventListener('beforeunload', () => {
            eventListenerManager.cleanup();
            cacheManager.clear();
        });
        
        // 页面隐藏时暂停不必要的操作
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                // 页面隐藏时暂停动画和定时器
                if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                    console.log('📱 页面已隐藏，暂停后台操作');
                }
            } else {
                // 页面显示时恢复操作
                if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                    console.log('📱 页面已显示，恢复操作');
                }
            }
        });
        
    } catch (error) {
        errorHandler.logError(error, '页面初始化');
    }
});

// AI工具功能
function openAITool(toolName) {
    const urls = {
        'chatgpt': 'https://chat.openai.com',
        'copilot': 'https://copilot.microsoft.com',
        'midjourney': 'https://www.midjourney.com',
        'claude': 'https://claude.ai'
    };
    
    if (urls[toolName]) {
        window.open(urls[toolName], '_blank');
    }
}

// 快捷工具功能
function openTool(toolName) {
    const urls = {
        'calculator': 'https://www.bing.com/search?q=calculator',
        'translator': 'https://www.bing.com/translator',
        'notes': 'data:text/html,<html><head><title>记事本</title></head><body><textarea style="width:100%;height:100vh;border:none;padding:20px;font-family:monospace;font-size:14px;" placeholder="在这里输入您的笔记..."></textarea></body></html>',
        'timer': 'https://www.bing.com/search?q=timer'
    };
    
    if (urls[toolName]) {
        window.open(urls[toolName], '_blank');
    }
}

// 书签功能
function openBookmark(url) {
    window.open(url, '_blank');
}

// 安全的对话框工具
const dialogUtils = {
    showPrompt: function(title, placeholder = '', callback) {
        const overlay = document.createElement('div');
        overlay.style.cssText = `
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            z-index: 10000;
            display: flex;
            align-items: center;
            justify-content: center;
        `;
        
        const dialog = document.createElement('div');
        dialog.style.cssText = `
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.3);
            max-width: 400px;
            width: 90%;
        `;
        
        dialog.innerHTML = `
            <h3 style="margin: 0 0 15px 0; color: #333;">${securityUtils.sanitizeHTML(title)}</h3>
            <input type="text" id="promptInput" placeholder="${securityUtils.sanitizeHTML(placeholder)}" 
                   style="width: 100%; padding: 10px; border: 1px solid #ddd; border-radius: 4px; margin-bottom: 15px;">
            <div style="text-align: right;">
                <button id="cancelBtn" style="margin-right: 10px; padding: 8px 16px; border: 1px solid #ddd; background: white; border-radius: 4px; cursor: pointer;">取消</button>
                <button id="confirmBtn" style="padding: 8px 16px; background: #0078d4; color: white; border: none; border-radius: 4px; cursor: pointer;">确定</button>
            </div>
        `;
        
        overlay.appendChild(dialog);
        document.body.appendChild(overlay);
        
        const input = dialog.querySelector('#promptInput');
        const confirmBtn = dialog.querySelector('#confirmBtn');
        const cancelBtn = dialog.querySelector('#cancelBtn');
        
        input.focus();
        
        const cleanup = () => {
            document.body.removeChild(overlay);
        };
        
        confirmBtn.onclick = () => {
            const value = input.value.trim();
            cleanup();
            callback(value || null);
        };
        
        cancelBtn.onclick = () => {
            cleanup();
            callback(null);
        };
        
        input.onkeydown = (e) => {
            if (e.key === 'Enter') {
                confirmBtn.click();
            } else if (e.key === 'Escape') {
                cancelBtn.click();
            }
        };
    },
    
    showAlert: function(message, type = 'info') {
        const notification = document.createElement('div');
        const bgColor = type === 'error' ? '#f44336' : type === 'success' ? '#4CAF50' : '#2196F3';
        
        notification.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            background: ${bgColor};
            color: white;
            padding: 15px 20px;
            border-radius: 5px;
            z-index: 10001;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
            max-width: 300px;
            word-wrap: break-word;
        `;
        
        notification.textContent = message;
        document.body.appendChild(notification);
        
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 3000);
    }
};

function addBookmark() {
    dialogUtils.showPrompt('书签名称', '请输入书签名称', (name) => {
        if (name) {
            dialogUtils.showPrompt('书签URL', 'https://', (url) => {
                if (url && securityUtils.isValidURL(url)) {
                    // 保存书签到本地存储
                    const bookmarks = JSON.parse(localStorage.getItem('customBookmarks') || '[]');
                    bookmarks.push({ name: securityUtils.sanitizeHTML(name), url: url });
                    localStorage.setItem('customBookmarks', JSON.stringify(bookmarks));
                    
                    dialogUtils.showAlert(`书签 "${name}" 已添加！`, 'success');
                } else if (url) {
                    dialogUtils.showAlert('请输入有效的URL地址', 'error');
                }
            });
        }
    });
}

// 背景自定义功能
function initializeCustomBackground() {
    const savedBackground = localStorage.getItem('customBackground');
    const savedOpacity = localStorage.getItem('backgroundOpacity');
    
    if (savedBackground) {
        applyCustomBackground(savedBackground);
    }
    
    if (savedOpacity) {
        document.getElementById('backgroundOpacity').value = savedOpacity;
        adjustBackgroundOpacity(savedOpacity);
    }
}

function uploadBackground(event) {
    const file = event.target.files[0];
    if (file && file.type.startsWith('image/')) {
        const reader = new FileReader();
        reader.onload = function(e) {
            const imageData = e.target.result;
            localStorage.setItem('customBackground', imageData);
            applyCustomBackground(imageData);
        };
        reader.readAsDataURL(file);
    }
}

function applyCustomBackground(imageData) {
    document.body.classList.add('custom-background');
    document.body.style.setProperty('--custom-bg-image', `url(${imageData})`);
}

function resetBackground() {
    document.body.classList.remove('custom-background');
    document.body.style.removeProperty('--custom-bg-image');
    localStorage.removeItem('customBackground');
    document.getElementById('backgroundUpload').value = '';
}

function adjustBackgroundOpacity(value) {
    document.body.style.setProperty('--bg-opacity', value);
    localStorage.setItem('backgroundOpacity', value);
}

// 高级缓存管理
const cacheManager = {
    cache: new Map(),
    maxSize: 100, // 最大缓存条目数
    
    set: function(key, value, ttl = 300000) { // 默认5分钟缓存
        // 检查缓存大小限制
        if (this.cache.size >= this.maxSize) {
            const firstKey = this.cache.keys().next().value;
            this.cache.delete(firstKey);
        }
        
        const expiry = Date.now() + ttl;
        this.cache.set(key, { value, expiry, accessTime: Date.now() });
    },
    
    get: function(key) {
        const item = this.cache.get(key);
        if (!item) return null;
        
        if (Date.now() > item.expiry) {
            this.cache.delete(key);
            return null;
        }
        
        // 更新访问时间
        item.accessTime = Date.now();
        return item.value;
    },
    
    clear: function() {
        this.cache.clear();
    },
    
    // 清理过期缓存
    cleanup: function() {
        const now = Date.now();
        for (const [key, item] of this.cache.entries()) {
            if (now > item.expiry) {
                this.cache.delete(key);
            }
        }
    },
    
    // 获取缓存统计
    getStats: function() {
        return {
            size: this.cache.size,
            maxSize: this.maxSize,
            hitRate: this.hitCount / (this.hitCount + this.missCount) || 0
        };
    }
};

// 请求管理器
const requestManager = {
    pendingRequests: new Map(),
    requestQueue: [],
    maxConcurrent: 6,
    activeRequests: 0,
    
    // 防重复请求
    dedupedFetch: function(url, options = {}) {
        const key = `${url}_${JSON.stringify(options)}`;
        
        if (this.pendingRequests.has(key)) {
            return this.pendingRequests.get(key);
        }
        
        const promise = this.queuedFetch(url, options)
            .finally(() => {
                this.pendingRequests.delete(key);
            });
        
        this.pendingRequests.set(key, promise);
        return promise;
    },
    
    // 队列化请求
    queuedFetch: function(url, options = {}) {
        return new Promise((resolve, reject) => {
            this.requestQueue.push({ url, options, resolve, reject });
            this.processQueue();
        });
    },
    
    // 处理请求队列
    processQueue: function() {
        if (this.activeRequests >= this.maxConcurrent || this.requestQueue.length === 0) {
            return;
        }
        
        const { url, options, resolve, reject } = this.requestQueue.shift();
        this.activeRequests++;
        
        fetch(url, options)
            .then(resolve)
            .catch(reject)
            .finally(() => {
                this.activeRequests--;
                this.processQueue();
            });
    }
};

// 虚拟滚动管理器
const virtualScrollManager = {
    itemHeight: 60,
    visibleItems: 10,
    buffer: 5,
    
    init: function(container, items, renderItem) {
        this.container = container;
        this.items = items;
        this.renderItem = renderItem;
        this.scrollTop = 0;
        
        this.setupScrollListener();
        this.render();
    },
    
    setupScrollListener: function() {
        // 使用requestAnimationFrame优化滚动性能
        let ticking = false;
        
        this.container.addEventListener('scroll', () => {
            if (!ticking) {
                requestAnimationFrame(() => {
                    this.scrollTop = this.container.scrollTop;
                    this.render();
                    ticking = false;
                });
                ticking = true;
            }
        }, { passive: true }); // 使用passive监听器提升性能
    },
    
    render: function() {
        const startIndex = Math.max(0, Math.floor(this.scrollTop / this.itemHeight) - this.buffer);
        const endIndex = Math.min(this.items.length - 1, startIndex + this.visibleItems + this.buffer * 2);
        
        // 清空容器
        this.container.innerHTML = '';
        
        // 创建占位空间
        const topSpacer = document.createElement('div');
        topSpacer.style.height = `${startIndex * this.itemHeight}px`;
        this.container.appendChild(topSpacer);
        
        // 渲染可见项目
        for (let i = startIndex; i <= endIndex; i++) {
            const item = this.renderItem(this.items[i], i);
            this.container.appendChild(item);
        }
        
        // 创建底部占位空间
        const bottomSpacer = document.createElement('div');
        bottomSpacer.style.height = `${(this.items.length - endIndex - 1) * this.itemHeight}px`;
        this.container.appendChild(bottomSpacer);
    }
};

// 高级懒加载和渐进式图片加载管理
const lazyLoadManager = {
    observer: null,
    
    init: function() {
        if ('IntersectionObserver' in window) {
            this.observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const img = entry.target;
                        if (img.dataset.src) {
                            this.loadProgressiveImage(img);
                            this.observer.unobserve(img);
                        }
                    }
                });
            }, {
                rootMargin: '50px' // 提前50px开始加载
            });
        }
    },
    
    observe: function(element) {
        if (this.observer) {
            this.observer.observe(element);
        }
    },
    
    // 渐进式图片加载
    loadProgressiveImage: function(img) {
        const container = img.parentElement;
        const lowQualitySrc = img.dataset.lowSrc;
        const highQualitySrc = img.dataset.src;
        
        if (lowQualitySrc && highQualitySrc) {
            // 先加载低质量版本
            const lowQualityImg = new Image();
            lowQualityImg.onload = () => {
                img.src = lowQualitySrc;
                img.classList.add('low-quality');
                
                // 然后加载高质量版本
                const highQualityImg = new Image();
                highQualityImg.onload = () => {
                    img.src = highQualitySrc;
                    img.classList.remove('low-quality');
                    img.classList.add('high-quality', 'loaded');
                };
                highQualityImg.src = highQualitySrc;
            };
            lowQualityImg.src = lowQualitySrc;
        } else {
            // 普通懒加载
            img.src = img.dataset.src;
            img.removeAttribute('data-src');
        }
    }
};

// 骨架屏管理器
const skeletonManager = {
    // 创建骨架屏
    createSkeleton: function(type = 'card') {
        const skeleton = document.createElement('div');
        skeleton.className = `skeleton skeleton-${type}`;
        
        if (type === 'card') {
            skeleton.innerHTML = `
                <div class="skeleton-text long"></div>
                <div class="skeleton-text medium"></div>
                <div class="skeleton-text short"></div>
            `;
        } else if (type === 'text') {
            skeleton.className = 'skeleton skeleton-text';
        }
        
        return skeleton;
    },
    
    // 显示骨架屏
    showSkeleton: function(container, count = 3, type = 'card') {
        container.innerHTML = '';
        for (let i = 0; i < count; i++) {
            container.appendChild(this.createSkeleton(type));
        }
    },
    
    // 隐藏骨架屏
    hideSkeleton: function(container) {
        const skeletons = container.querySelectorAll('.skeleton');
        skeletons.forEach(skeleton => {
            skeleton.style.opacity = '0';
            setTimeout(() => skeleton.remove(), 300);
        });
    }
};

// 性能提示管理器
const performanceTipManager = {
    tips: [
        '💡 使用Ctrl+D将此页面添加到书签',
        '🚀 页面已启用PWA，可以安装到桌面',
        '⚡ 启用了智能缓存，提升加载速度',
        '🔒 页面采用了安全策略保护您的隐私',
        '📱 支持响应式设计，适配各种设备'
    ],
    
    showRandomTip: function() {
        const tip = this.tips[Math.floor(Math.random() * this.tips.length)];
        this.showTip(tip);
    },
    
    showTip: function(message, duration = 5000) {
        const existingTip = document.querySelector('.performance-tip');
        if (existingTip) {
            existingTip.remove();
        }
        
        const tipElement = document.createElement('div');
        tipElement.className = 'performance-tip';
        tipElement.innerHTML = `
            ${message}
            <button class="close-btn" onclick="this.parentElement.remove()">×</button>
        `;
        
        document.body.appendChild(tipElement);
        
        // 显示动画
        setTimeout(() => tipElement.classList.add('show'), 100);
        
        // 自动隐藏
        setTimeout(() => {
            tipElement.classList.remove('show');
            setTimeout(() => tipElement.remove(), 300);
        }, duration);
    }
};

// 天气定位功能
let currentLocation = '北京';

function initializeGeolocation() {
    const savedLocation = localStorage.getItem('weatherLocation');
    if (savedLocation) {
        currentLocation = savedLocation;
        updateWeatherLocation(currentLocation);
    } else {
        // 首次访问时尝试自动定位
        autoLocate(true);
    }
}

function toggleLocationSettings() {
    const settings = document.getElementById('locationSettings');
    settings.classList.toggle('show');
}

function autoLocate(silent = false) {
    if (navigator.geolocation) {
        // 显示定位中状态
        const locationElement = document.querySelector('.weather-location');
        if (locationElement && !silent) {
            locationElement.textContent = '定位中... 🔄';
        }
        
        navigator.geolocation.getCurrentPosition(
            function(position) {
                const lat = position.coords.latitude;
                const lon = position.coords.longitude;
                
                // 使用反向地理编码获取城市名称
                reverseGeocode(lat, lon, silent);
            },
            function(error) {
                if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                    console.error('定位错误:', error);
                }
                if (!silent) {
                    dialogUtils.showAlert('定位失败，请检查位置权限或手动选择城市', 'error');
                }
                // 定位失败时恢复当前位置显示
                if (locationElement) {
                    locationElement.textContent = `${currentLocation} 📍`;
                }
            },
            {
                enableHighAccuracy: true,
                timeout: 10000,
                maximumAge: 300000 // 5分钟缓存
            }
        );
    } else {
        if (!silent) {
            dialogUtils.showAlert('您的浏览器不支持地理定位，请手动选择城市', 'error');
        }
    }
}

// 反向地理编码函数
function reverseGeocode(lat, lon, silent = false) {
    // 使用免费的地理编码服务
    fetch(`https://api.bigdatacloud.net/data/reverse-geocode-client?latitude=${lat}&longitude=${lon}&localityLanguage=zh`)
        .then(response => response.json())
        .then(data => {
            let cityName = data.city || data.locality || data.principalSubdivision;
            if (!cityName && data.countryName === 'China') {
                // 如果没有获取到城市名，使用一些常见的中国城市
                const chineseCities = ['北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '武汉'];
                cityName = chineseCities[Math.floor(Math.random() * chineseCities.length)];
            } else if (!cityName) {
                cityName = '北京'; // 默认城市
            }
            
            currentLocation = cityName;
            updateWeatherLocation(currentLocation);
            localStorage.setItem('weatherLocation', currentLocation);
            localStorage.setItem('lastLocationUpdate', Date.now().toString());
            
            if (!silent) {
                document.getElementById('locationSettings').classList.remove('show');
                showLocationNotification(`已自动定位到: ${currentLocation}`);
            }
            
            // 更新天气信息
            updateWeather();
        })
        .catch(error => {
            if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                console.error('地理编码失败:', error);
            }
            // 使用备用方案
            const fallbackCities = ['北京', '上海', '广州', '深圳'];
            const fallbackCity = fallbackCities[Math.floor(Math.random() * fallbackCities.length)];
            
            currentLocation = fallbackCity;
            updateWeatherLocation(currentLocation);
            
            if (!silent) {
                showLocationNotification(`定位服务不可用，已设置为: ${currentLocation}`);
            }
        });
}

function setManualLocation() {
    const input = document.getElementById('manualLocation');
    const location = input.value.trim();
    
    if (location) {
        // 验证城市名称
        if (validateCityName(location)) {
            currentLocation = location;
            updateWeatherLocation(currentLocation);
            localStorage.setItem('weatherLocation', currentLocation);
            localStorage.setItem('lastLocationUpdate', Date.now().toString());
            
            input.value = '';
            document.getElementById('locationSettings').classList.remove('show');
            
            showLocationNotification(`已设置位置为: ${currentLocation}`);
            
            // 更新天气信息
            updateWeather();
        } else {
            showLocationNotification('请输入有效的城市名称', 'error');
        }
    } else {
        showLocationNotification('请输入城市名称', 'error');
    }
}

// 验证城市名称
function validateCityName(cityName) {
    // 简单的城市名称验证
    const chineseCityPattern = /^[\u4e00-\u9fa5]{2,10}$/;
    const englishCityPattern = /^[a-zA-Z\s]{2,50}$/;
    
    return chineseCityPattern.test(cityName) || englishCityPattern.test(cityName);
}

// 显示位置通知
function showLocationNotification(message, type = 'success') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `location-notification ${type}`;
    notification.textContent = message;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: ${type === 'error' ? '#ff4757' : '#2ed573'};
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.2);
        z-index: 10000;
        font-size: 14px;
        font-weight: 500;
        transform: translateX(100%);
        transition: transform 0.3s ease;
    `;
    
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            if (notification.parentNode) {
                notification.parentNode.removeChild(notification);
            }
        }, 300);
    }, 3000);
 }

// 初始化城市搜索功能
function initializeCitySearch() {
    const input = document.getElementById('manualLocation');
    const suggestions = document.getElementById('citySuggestions');
    let currentHighlight = -1;
    
    // 常用城市列表
    const popularCities = [
        '北京', '上海', '广州', '深圳', '杭州', '南京', '成都', '武汉',
        '西安', '重庆', '天津', '苏州', '长沙', '郑州', '青岛', '大连',
        '宁波', '厦门', '福州', '无锡', '合肥', '昆明', '哈尔滨', '济南',
        '石家庄', '长春', '南昌', '贵阳', '太原', '兰州', '呼和浩特', '银川',
        '西宁', '拉萨', '乌鲁木齐', '海口', '三亚', '香港', '澳门', '台北'
    ];
    
    // 使用防抖优化输入性能
    const debouncedCitySearch = performanceUtils.debounce(function(value) {
        currentHighlight = -1;
        
        if (value.length === 0) {
            hideSuggestions();
            return;
        }
        
        // 过滤匹配的城市
        const matches = popularCities.filter(city => 
            city.includes(value) || city.toLowerCase().includes(value.toLowerCase())
        ).slice(0, 8); // 最多显示8个建议
        
        if (matches.length > 0) {
            showSuggestions(matches);
        } else {
            hideSuggestions();
        }
    }, 150); // 150ms防抖延迟
    
    input.addEventListener('input', function() {
        const value = this.value.trim();
        debouncedCitySearch(value);
    });
    
    input.addEventListener('keydown', function(e) {
        const items = suggestions.querySelectorAll('.city-suggestion-item');
        
        switch(e.key) {
            case 'ArrowDown':
                e.preventDefault();
                currentHighlight = Math.min(currentHighlight + 1, items.length - 1);
                updateHighlight(items);
                break;
            case 'ArrowUp':
                e.preventDefault();
                currentHighlight = Math.max(currentHighlight - 1, -1);
                updateHighlight(items);
                break;
            case 'Enter':
                e.preventDefault();
                if (currentHighlight >= 0 && items[currentHighlight]) {
                    selectCity(items[currentHighlight].textContent);
                } else {
                    setManualLocation();
                }
                break;
            case 'Escape':
                hideSuggestions();
                break;
        }
    });
    
    // 点击外部隐藏建议
    document.addEventListener('click', function(e) {
        if (!input.contains(e.target) && !suggestions.contains(e.target)) {
            hideSuggestions();
        }
    });
    
    function showSuggestions(cities) {
        suggestions.innerHTML = '';
        cities.forEach(city => {
            const item = document.createElement('div');
            item.className = 'city-suggestion-item';
            item.textContent = city;
            item.addEventListener('click', () => selectCity(city));
            suggestions.appendChild(item);
        });
        suggestions.style.display = 'block';
    }
    
    function hideSuggestions() {
        suggestions.style.display = 'none';
        currentHighlight = -1;
    }
    
    function updateHighlight(items) {
        items.forEach((item, index) => {
            item.classList.toggle('highlighted', index === currentHighlight);
        });
    }
    
    function selectCity(cityName) {
        input.value = cityName;
        hideSuggestions();
        setManualLocation();
    }
}

function updateWeatherLocation(location) {
    const locationElement = document.querySelector('.weather-location');
    if (locationElement) {
        locationElement.textContent = `${location} 📍`;
    }
}

// 点击外部关闭定位设置
document.addEventListener('click', function(event) {
    const locationSettings = document.getElementById('locationSettings');
    const weatherLocation = document.querySelector('.weather-location');
    
    if (locationSettings && !locationSettings.contains(event.target) && 
        !weatherLocation.contains(event.target)) {
        locationSettings.classList.remove('show');
    }
});

// 侧边栏切换功能
function toggleSidebar(side) {
    const body = document.body;
    const className = `${side}-sidebar-visible`;
    
    if (body.classList.contains(className)) {
        body.classList.remove(className);
    } else {
        // 关闭另一侧的侧边栏
        const otherSide = side === 'left' ? 'right' : 'left';
        body.classList.remove(`${otherSide}-sidebar-visible`);
        // 打开当前侧边栏
        body.classList.add(className);
    }
}

// 新增：侧边栏缩进功能
function toggleSidebarCollapse(side) {
    const body = document.body;
    const sidebar = document.querySelector(`.${side}-sidebar`);
    const collapseClassName = `${side}-sidebar-collapsed`;
    
    if (body.classList.contains(collapseClassName)) {
        // 展开侧边栏
        body.classList.remove(collapseClassName);
        sidebar.classList.remove('collapsed');
    } else {
        // 缩进侧边栏
        body.classList.add(collapseClassName);
        sidebar.classList.add('collapsed');
    }
    
    // 保存缩进状态到本地存储
    localStorage.setItem(`${side}SidebarCollapsed`, body.classList.contains(collapseClassName));
}

// 响应式处理
function handleResize() {
    const width = window.innerWidth;
    const body = document.body;
    
    if (width > 1200) {
        // 大屏幕时移除所有侧边栏切换类
        body.classList.remove('left-sidebar-visible', 'right-sidebar-visible');
        // 恢复缩进状态
        loadSidebarStates();
    } else {
        // 移动端时移除缩进状态
        body.classList.remove('left-sidebar-collapsed', 'right-sidebar-collapsed');
        document.querySelector('.left-sidebar').classList.remove('collapsed');
        document.querySelector('.right-sidebar').classList.remove('collapsed');
    }
}

// 加载侧边栏状态
function loadSidebarStates() {
    const leftCollapsed = localStorage.getItem('leftSidebarCollapsed') === 'true';
    const rightCollapsed = localStorage.getItem('rightSidebarCollapsed') === 'true';
    
    if (window.innerWidth > 1200) {
        if (leftCollapsed) {
            document.body.classList.add('left-sidebar-collapsed');
            document.querySelector('.left-sidebar').classList.add('collapsed');
        }
        if (rightCollapsed) {
            document.body.classList.add('right-sidebar-collapsed');
            document.querySelector('.right-sidebar').classList.add('collapsed');
        }
    }
}

// 监听窗口大小变化
window.addEventListener('resize', handleResize);

// 点击外部关闭侧边栏（移动端）
document.addEventListener('click', function(event) {
    const leftSidebar = document.querySelector('.left-sidebar');
    const rightSidebar = document.querySelector('.right-sidebar');
    const toggleButtons = document.querySelectorAll('.sidebar-toggle');
    
    let clickedToggle = false;
    toggleButtons.forEach(button => {
        if (button.contains(event.target)) {
            clickedToggle = true;
        }
    });
    
    if (!clickedToggle && window.innerWidth <= 1200) {
        if (leftSidebar && !leftSidebar.contains(event.target)) {
            document.body.classList.remove('left-sidebar-visible');
        }
        if (rightSidebar && !rightSidebar.contains(event.target)) {
            document.body.classList.remove('right-sidebar-visible');
        }
    }
});

// 初始化页面
function initializePage() {
    renderSites();
    renderNews();
    updateWeather();
    setupSearch();
}

// 渲染网站卡片
function renderSites() {
    const sitesGrid = document.getElementById('sitesGrid');
    const sites = getSavedSites() || defaultSites;
    
    // 显示骨架屏
    skeletonManager.showSkeleton(sitesGrid, Math.min(sites.length, 8), 'card');
    
    // 模拟加载延迟以展示骨架屏效果
    setTimeout(() => {
        // 使用文档片段优化DOM操作
        const fragment = document.createDocumentFragment();
        
        sites.forEach(site => {
            const siteCard = document.createElement('a');
            siteCard.className = 'site-card';
            siteCard.href = site.url;
            siteCard.target = '_blank';
            
            const siteIcon = document.createElement('div');
            siteIcon.className = 'site-icon';
            siteIcon.textContent = site.icon;
            
            const siteName = document.createElement('div');
            siteName.className = 'site-name';
            siteName.textContent = securityUtils.sanitizeHTML(site.name);
            
            siteCard.appendChild(siteIcon);
            siteCard.appendChild(siteName);
            fragment.appendChild(siteCard);
        });
        
        // 隐藏骨架屏并显示内容
        skeletonManager.hideSkeleton(sitesGrid);
        setTimeout(() => {
            sitesGrid.appendChild(fragment);
        }, 300);
    }, 400);
}

// 渲染新闻卡片
function renderNews() {
    const newsGrid = document.getElementById('newsGrid');
    
    // 显示骨架屏
    skeletonManager.showSkeleton(newsGrid, Math.min(mockNews.length, 6), 'card');
    
    // 模拟加载延迟以展示骨架屏效果
    setTimeout(() => {
        try {
            // 使用文档片段优化DOM操作
            const fragment = document.createDocumentFragment();
            
            mockNews.forEach(news => {
                const newsCard = document.createElement('div');
                newsCard.className = 'news-card';
                
                // 创建新闻图片
                const newsImage = document.createElement('div');
                if (news.image) {
                    const img = document.createElement('img');
                    img.src = news.image;
                    img.alt = securityUtils.sanitizeHTML(news.title);
                    img.className = 'news-image';
                    newsImage.appendChild(img);
                } else {
                    newsImage.className = 'news-image';
                }
                
                // 创建新闻内容
                const newsContent = document.createElement('div');
                newsContent.className = 'news-content';
                
                const newsTitle = document.createElement('h3');
                newsTitle.className = 'news-title';
                newsTitle.textContent = securityUtils.sanitizeHTML(news.title);
                
                const newsSummary = document.createElement('p');
                newsSummary.className = 'news-summary';
                newsSummary.textContent = securityUtils.sanitizeHTML(news.summary);
                
                const newsMeta = document.createElement('div');
                newsMeta.className = 'news-meta';
                
                const newsSource = document.createElement('span');
                newsSource.className = 'news-source';
                newsSource.textContent = securityUtils.sanitizeHTML(news.source);
                
                const newsTime = document.createElement('span');
                newsTime.className = 'news-time';
                newsTime.textContent = news.time;
                
                newsMeta.appendChild(newsSource);
                newsMeta.appendChild(newsTime);
                
                newsContent.appendChild(newsTitle);
                newsContent.appendChild(newsSummary);
                newsContent.appendChild(newsMeta);
                
                newsCard.appendChild(newsImage);
                newsCard.appendChild(newsContent);
                fragment.appendChild(newsCard);
            });
            
            // 隐藏骨架屏并显示内容
            skeletonManager.hideSkeleton(newsGrid);
            setTimeout(() => {
                newsGrid.appendChild(fragment);
            }, 300);
        } catch (error) {
            if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
                console.error('渲染新闻时出错:', error);
            }
            skeletonManager.hideSkeleton(newsGrid);
            newsGrid.innerHTML = '<div class="error-message">新闻加载失败</div>';
        }
    }, 600);
}

// 设置搜索功能 - 使用防抖优化
function setupSearch() {
    const searchInput = document.getElementById('searchInput');
    const searchSuggestions = document.getElementById('searchSuggestions');
    
    // 防抖搜索建议
    const debouncedSearch = performanceUtils.debounce(function(query) {
        if (query.length > 0) {
            showSearchSuggestions(query);
        } else {
            hideSearchSuggestions();
        }
    }, 200); // 减少防抖延迟到200ms，提升响应速度
    
    // 优化输入事件处理，支持输入法
    let isComposing = false;
    
    searchInput.addEventListener('compositionstart', function() {
        isComposing = true;
    });
    
    searchInput.addEventListener('compositionend', function(e) {
        isComposing = false;
        const query = securityUtils.sanitizeHTML(e.target.value.trim());
        debouncedSearch(query);
    });
    
    searchInput.addEventListener('input', function(e) {
        if (!isComposing) {
            const query = securityUtils.sanitizeHTML(e.target.value.trim());
            debouncedSearch(query);
        }
    });
    
    searchInput.addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            const query = securityUtils.sanitizeHTML(e.target.value);
            performSearch(query);
        }
    });
    
    // 使用事件委托优化点击处理
    document.addEventListener('click', function(e) {
        if (!e.target.closest('.search-box')) {
            hideSearchSuggestions();
        }
    });
}

// 显示搜索建议
function showSearchSuggestions(query) {
    const suggestionsContainer = document.getElementById('searchSuggestions');
    const filteredSuggestions = searchSuggestions.filter(suggestion => 
        suggestion.toLowerCase().includes(query.toLowerCase())
    );
    
    if (filteredSuggestions.length > 0) {
        suggestionsContainer.innerHTML = filteredSuggestions.map(suggestion => {
            const safeSuggestion = securityUtils.sanitizeHTML(suggestion);
            return `
                <div class="suggestion-item" onclick="selectSuggestion('${safeSuggestion}')">
                    ${safeSuggestion}
                </div>
            `;
        }).join('');
        suggestionsContainer.style.display = 'block';
    } else {
        hideSearchSuggestions();
    }
}

// 隐藏搜索建议
function hideSearchSuggestions() {
    const suggestionsContainer = document.getElementById('searchSuggestions');
    suggestionsContainer.style.display = 'none';
}

// 选择搜索建议
function selectSuggestion(suggestion) {
    const searchInput = document.getElementById('searchInput');
    searchInput.value = suggestion;
    hideSearchSuggestions();
    performSearch(suggestion);
}

// 执行搜索
function performSearch(query) {
    if (query.trim()) {
        const searchUrl = `https://www.bing.com/search?q=${encodeURIComponent(query)}`;
        window.open(searchUrl, '_blank');
    }
}

// 更新天气信息
function updateWeather() {
    // 使用当前选择的位置，如果没有则使用默认位置
    const currentCity = currentLocation || '北京';
    
    // 模拟天气数据
    const weatherData = {
        temperature: Math.floor(Math.random() * 20) + 10,
        icon: getWeatherIcon()
    };
    
    const weatherWidget = document.getElementById('weatherWidget');
    weatherWidget.querySelector('.weather-temp').textContent = `${weatherData.temperature}°C`;
    weatherWidget.querySelector('.weather-location').textContent = `${currentCity} 📍`;
    weatherWidget.querySelector('.weather-icon').textContent = weatherData.icon;
}

// 获取天气图标
function getWeatherIcon() {
    const icons = ['☀️', '⛅', '🌤️', '🌦️', '🌧️', '⛈️', '🌨️'];
    return icons[Math.floor(Math.random() * icons.length)];
}

// 刷新新闻
function refreshNews() {
    // 模拟刷新动画
    const refreshBtn = document.querySelector('.refresh-btn');
    refreshBtn.style.transform = 'rotate(360deg)';
    
    setTimeout(() => {
        renderNews();
        refreshBtn.style.transform = 'rotate(0deg)';
    }, 500);
}

// 切换设置面板
function toggleSettings() {
    const settingsPanel = document.getElementById('settingsPanel');
    const isVisible = settingsPanel.style.display === 'flex';
    settingsPanel.style.display = isVisible ? 'none' : 'flex';
}

// 设置事件监听器
function setupEventListeners() {
    // 天气显示切换
    document.getElementById('showWeather').addEventListener('change', function(e) {
        const weatherWidget = document.getElementById('weatherWidget');
        weatherWidget.style.display = e.target.checked ? 'block' : 'none';
        saveUserSettings();
    });
    
    // 新闻显示切换
    document.getElementById('showNews').addEventListener('change', function(e) {
        const newsSection = document.querySelector('.news-section');
        newsSection.style.display = e.target.checked ? 'block' : 'none';
        saveUserSettings();
    });
    
    // 主题切换
    document.getElementById('themeSelect').addEventListener('change', function(e) {
        applyTheme(e.target.value);
        saveUserSettings();
    });
    
    // 设置面板点击外部关闭
    document.getElementById('settingsPanel').addEventListener('click', function(e) {
        if (e.target === this) {
            toggleSettings();
        }
    });
}

// 应用主题
function applyTheme(theme) {
    const body = document.body;
    body.classList.remove('dark-theme', 'light-theme');
    
    if (theme === 'dark') {
        body.classList.add('dark-theme');
    } else if (theme === 'light') {
        body.classList.add('light-theme');
    } else if (theme === 'auto') {
        // 检测系统主题
        if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
            body.classList.add('dark-theme');
        }
    }
}

// 保存用户设置
function saveUserSettings() {
    const settings = {
        showWeather: document.getElementById('showWeather').checked,
        showNews: document.getElementById('showNews').checked,
        theme: document.getElementById('themeSelect').value
    };
    
    localStorage.setItem('pageSettings', JSON.stringify(settings));
}

// 加载用户设置
function loadUserSettings() {
    const savedSettings = localStorage.getItem('pageSettings');
    if (savedSettings) {
        const settings = JSON.parse(savedSettings);
        
        document.getElementById('showWeather').checked = settings.showWeather !== false;
        document.getElementById('showNews').checked = settings.showNews !== false;
        document.getElementById('themeSelect').value = settings.theme || 'light';
        
        // 应用设置
        document.getElementById('weatherWidget').style.display = 
            settings.showWeather !== false ? 'block' : 'none';
        document.querySelector('.news-section').style.display = 
            settings.showNews !== false ? 'block' : 'none';
        applyTheme(settings.theme || 'light');
    }
}

// 获取保存的网站
function getSavedSites() {
    const savedSites = localStorage.getItem('quickAccessSites');
    return savedSites ? JSON.parse(savedSites) : null;
}

// 保存网站
function saveSites(sites) {
    localStorage.setItem('quickAccessSites', JSON.stringify(sites));
}

// 添加网站（可扩展功能）
function addSite(name, url, icon) {
    const sites = getSavedSites() || defaultSites;
    sites.push({ name, url, icon });
    saveSites(sites);
    renderSites();
}

// 删除网站（可扩展功能）
function removeSite(index) {
    const sites = getSavedSites() || defaultSites;
    sites.splice(index, 1);
    saveSites(sites);
    renderSites();
}

// 监听系统主题变化
if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', function(e) {
        const themeSelect = document.getElementById('themeSelect');
        if (themeSelect.value === 'auto') {
            applyTheme('auto');
        }
    });
}

// 添加一些动画效果
function addAnimations() {
    // 页面加载动画
    const cards = document.querySelectorAll('.site-card, .news-card');
    cards.forEach((card, index) => {
        card.style.opacity = '0';
        card.style.transform = 'translateY(20px)';
        
        setTimeout(() => {
            card.style.transition = 'all 0.5s ease';
            card.style.opacity = '1';
            card.style.transform = 'translateY(0)';
        }, index * 100);
    });
}

// 页面加载完成后添加动画
window.addEventListener('load', function() {
    setTimeout(addAnimations, 100);
});

// 添加键盘快捷键
document.addEventListener('keydown', function(e) {
    // Ctrl + K 聚焦搜索框
    if (e.ctrlKey && e.key === 'k') {
        e.preventDefault();
        document.getElementById('searchInput').focus();
    }
    
    // Esc 关闭设置面板
    if (e.key === 'Escape') {
        const settingsPanel = document.getElementById('settingsPanel');
        if (settingsPanel.style.display === 'flex') {
            toggleSettings();
        }
    }
});

// 添加右键菜单（可扩展功能）
document.addEventListener('contextmenu', function(e) {
    if (e.target.closest('.site-card')) {
        e.preventDefault();
        // 这里可以添加自定义右键菜单
        if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
            console.log('右键点击网站卡片');
        }
    }
});

// 定期更新天气信息
setInterval(updateWeather, 300000); // 每5分钟更新一次

// 添加错误处理
window.addEventListener('error', function(e) {
    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
        console.error('页面错误:', e.error);
    }
});

// 添加离线检测
window.addEventListener('online', function() {
    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
        console.log('网络已连接');
    }
});

window.addEventListener('offline', function() {
    if (typeof window !== 'undefined' && window.location.hostname === 'localhost') {
        console.log('网络已断开');
    }
});

// 学术文献搜索工具函数
function openAcademicTool(tool) {
    const academicUrls = {
        'cnki': 'https://www.cnki.net/',
        'wanfang': 'https://www.wanfangdata.com.cn/',
        'vip': 'https://www.cqvip.com/',
        'scholar': 'https://scholar.google.com/',
        'pubmed': 'https://pubmed.ncbi.nlm.nih.gov/',
        'ieee': 'https://ieeexplore.ieee.org/',
        'arxiv': 'https://arxiv.org/',
        'researchgate': 'https://www.researchgate.net/'
    };
    
    if (academicUrls[tool]) {
        window.open(academicUrls[tool], '_blank');
    }
}

// 学习资源函数
function openLearning(platform) {
    const learningUrls = {
        'coursera': 'https://www.coursera.org/',
        'edx': 'https://www.edx.org/',
        'khan': 'https://www.khanacademy.org/',
        'bilibili': 'https://www.bilibili.com/video/',
        'mooc': 'https://www.icourse163.org/',
        'xuetangx': 'https://www.xuetangx.com/'
    };
    
    if (learningUrls[platform]) {
        window.open(learningUrls[platform], '_blank');
    }
}

// 开发工具函数
function openDevTool(tool) {
    const devUrls = {
        'github': 'https://github.com/',
        'stackoverflow': 'https://stackoverflow.com/',
        'codepen': 'https://codepen.io/',
        'jsfiddle': 'https://jsfiddle.net/',
        'regex101': 'https://regex101.com/',
        'jsonlint': 'https://jsonlint.com/'
    };
    
    if (devUrls[tool]) {
        window.open(devUrls[tool], '_blank');
    }
}

// 生产力工具函数
function openProductivity(tool) {
    const productivityUrls = {
        'notion': 'https://www.notion.so/',
        'trello': 'https://trello.com/',
        'figma': 'https://www.figma.com/',
        'canva': 'https://www.canva.com/',
        'grammarly': 'https://www.grammarly.com/',
        'deepl': 'https://www.deepl.com/translator'
    };
    
    if (productivityUrls[tool]) {
        window.open(productivityUrls[tool], '_blank');
    }
}

// 扩展快捷工具函数
function openTool(tool) {
    const toolUrls = {
        'calculator': 'https://www.calculator.net/',
        'translator': 'https://translate.google.com/',
        'notes': 'data:text/html,<html><head><title>记事本</title></head><body><textarea style="width:100%;height:100vh;border:none;outline:none;font-family:monospace;font-size:14px;padding:20px;" placeholder="在这里输入您的笔记..."></textarea></body></html>',
        'timer': 'https://www.online-stopwatch.com/',
        'calendar': 'https://calendar.google.com/',
        'color-picker': 'data:text/html,<html><head><title>取色器</title></head><body style="margin:0;padding:20px;font-family:Arial;"><h2>颜色选择器</h2><input type="color" id="colorPicker" style="width:100px;height:50px;"><div id="colorInfo" style="margin-top:20px;font-size:18px;"></div><script>document.getElementById("colorPicker").addEventListener("input",function(e){document.getElementById("colorInfo").innerHTML="颜色值: "+e.target.value;document.body.style.backgroundColor=e.target.value;});</script></body></html>',
        'qr-generator': 'https://www.qr-code-generator.com/',
        'password-generator': 'https://passwordsgenerator.net/',
        'unit-converter': 'https://www.unitconverters.net/',
        'base64': 'https://www.base64encode.org/',
        'json-formatter': 'https://jsonformatter.curiousconcept.com/',
        'markdown-editor': 'https://dillinger.io/'
    };
    
    if (toolUrls[tool]) {
        window.open(toolUrls[tool], '_blank');
    }
}